<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            let arr = [1, 2, 3, 4, 5];
            // arr.copyWithin(2, 0, 2);
            // console.log(arr); // [1, 2, 1, 2, 5]
            // let arr1 = [1, 2, 3, 4, 5];

            // arr1.copyWithin(-2, -5, -3);
            // console.log(arr1);
            // let arr2 = [1, 2, 3, 4, 5];

            // arr2.copyWithin(3, 1);
            // console.log(arr2); // [1,1,2,3,4]
            // let arr3 = [1, 2, 3, 4, 5];

            // arr3.copyWithin(1, 0);
            // console.log(arr3);
            // let arr4 = [1, 2, 3, 4, 5];
            // arr4.copyWithin(1, 3);
            // console.log(arr4); // [1, 4, 5, 4, 5]
            Array.prototype.myCopyWithin = function (target, start = 0, end = this.length) {
                let newArr = [];
                if (target < 0) target = this.length + target;
                if (start < 0) start = this.length + start;
                if (end < 0) end = this.length + end;
                for (let i = start; i < end; i++) {
                    newArr.push(this[i]);
                }
                let arrLength = newArr.length;
                let k = 0;
                // 同时判断赋值的区间和待拷贝数组的长度的大小
                let len = arrLength < this.length - target ? target + arrLength : this.length;
                for (; target < len; target++) {
                    console.log(newArr[k]);
                    this[target] = newArr[k++];
                }
                return this;
            };
            arr.myCopyWithin(2, 0, 2);
            console.log(arr); // [1, 2, 1, 2, 5]
            let arr1 = [1, 2, 3, 4, 5];

            arr1.myCopyWithin(-2, -5, -3);
            console.log(arr1);
            let arr2 = [1, 2, 3, 4, 5];

            arr2.myCopyWithin(3, 1);
            console.log(arr2); // [1,1,2,3,4]
            let arr3 = [1, 2, 3, 4, 5];

            arr3.myCopyWithin(1, 0);
            console.log(arr3);
            let arr4 = [1, 2, 3, 4, 5];
            arr4.myCopyWithin(1, 3);
            console.log(arr4); // [1, 4, 5, 4, 5]
        </script>
    </body>
</html>
